import React,{useEffect}from 'react';
import { Button, Divider,Popover,Modal   } from 'antd';
import {
    SaveOutlined,
    DownloadOutlined,
    EyeOutlined,
    ZoomInOutlined,
    ZoomOutOutlined,
    UndoOutlined,
    RedoOutlined,
    DeleteOutlined,
    RollbackOutlined
} from '@ant-design/icons';
import domtoimage from 'dom-to-image';
import { saveAs } from 'file-saver';
import {useNavigate} from "react-router-dom";
const ZOOM_STEP = 0.2; // 每次缩放 20%
const MIN_ZOOM = 0.2;  // 最小缩放比例
const MAX_ZOOM = 4.0;  // 最大缩放比例

const ProcessTools = ({save,bpmnModeler}) => {
    const navigate = useNavigate();

    const [canUndo, setCanUndo] = React.useState(false);
    const [canRedo, setCanRedo] = React.useState(false);



    // 监听 CommandStack 变化
    useEffect(() => {
        if (!bpmnModeler) return;

        const commandStack = bpmnModeler.get('commandStack');
        const eventBus = bpmnModeler.get('eventBus');

        // 初始化按钮状态
        setCanUndo(commandStack.canUndo());
        setCanRedo(commandStack.canRedo());

        // 注册事件监听
        const updateState = () => {
            setCanUndo(commandStack.canUndo());
            setCanRedo(commandStack.canRedo());
        };

        eventBus.on('commandStack.changed', updateState);
        return () => eventBus.off('commandStack.changed', updateState);
    }, [bpmnModeler]);

    const saveHand = () => {
        save();
    }


    // 擦除当前选中元素
    const handleErase = () => {
        if (!bpmnModeler) return;
        Modal.confirm({
            title: '确认擦除全部内容',
            content: '确定要清除整个画布上的所有内容吗？此操作不可恢复！',
            onOk: () => {
                return new Promise((resolve, reject) => {
                    try {
                        const canvas = bpmnModeler.get('canvas');
                        const elementRegistry = bpmnModeler.get('elementRegistry');
                        const modeling = bpmnModeler.get('modeling');
                        // 获取所有元素并删除
                        const elements = elementRegistry.getAll();
                        elements.forEach((element) => {
                            if(element.type !== 'bpmn:Process') {
                                modeling.removeElements([element]);
                            }
                        });
                       canvas.zoom('fit-viewport', 'auto');
                        resolve()
                    }catch (e) {
                        console.error('擦除失败', e);
                        reject(e);
                    }
                })

            },
        });
    };


    const handlePreview =  () => {
        if (!bpmnModeler) return;

        try {
           bpmnModeler.saveXML({ format: true }, (err, xml) => {
                if (err) {
                    console.error('Failed to export XML', err);
                    Modal.error({
                        title: '错误',
                        content: '无法加载流程定义的 XML 内容。',
                    });
                } else {
                    Modal.info({
                        title: '流程定义 XML',
                        content: <pre style={{ maxHeight: '400px', overflow: 'auto' }}>{xml}</pre>,
                        width: '80%',
                    });
                }
            });
        } catch (err) {
            console.error('Failed to export XML', err);
        }
    };


    // 撤销操作
    const handleUndo = () => {
        if (!bpmnModeler || !canUndo) return;
        bpmnModeler.get('commandStack').undo();
    };

    // 恢复操作
    const handleRedo = () => {
        if (!bpmnModeler || !canRedo) return;
        bpmnModeler.get('commandStack').redo();
    };


    const handleZoomIn = () => {
        if (!bpmnModeler) return;

        const canvas = bpmnModeler.get('canvas');
        const currentZoom = canvas.zoom();
        let newZoom = currentZoom + ZOOM_STEP;

        // 限制最大缩放比例
        if (newZoom > MAX_ZOOM) {
            newZoom = MAX_ZOOM;
        }

        canvas.zoom(newZoom);
    };

    // 缩小画布
    const handleZoomOut = () => {
        if (!bpmnModeler) return;

        const canvas = bpmnModeler.get('canvas');
        const currentZoom = canvas.zoom();
        let newZoom = currentZoom - ZOOM_STEP;

        // 限制最小缩放比例
        if (newZoom < MIN_ZOOM) {
            newZoom = MIN_ZOOM;
        }

        canvas.zoom(newZoom);
    };


    const downloadHand = () => {
         console.log(bpmnModeler)
    }

// 下载为 BPMN 文件
    const handleDownloadBPMN =  () => {
        try {
             bpmnModeler.saveXML({ format: true }, (err, xml) => {
                 if (err) {
                     console.error('Failed to export BPMN', err);
                 } else {
                     const blob = new Blob([xml], { type: 'application/bpmn20-xml' });
                     saveAs(blob, 'diagram.bpmn');
                 }
             });

        } catch (err) {
            console.error('Failed to export BPMN', err);
        }
    };

    // 下载为 XML 文件
    const handleDownloadXML =  () => {
        try {
             bpmnModeler.saveXML({ format: true }, (err, xml) => {
                 if (err) {
                     console.error('Failed to export XML', err);
                 } else {
                     const blob = new Blob([xml], { type: 'application/xml' });
                     saveAs(blob, 'diagram.xml');
                 }
             });
        } catch (err) {
            console.error('Failed to export XML', err);
        }
    };

    // 下载为 SVG 文件
    const handleDownloadSVG =  () => {
        try {
             bpmnModeler.saveSVG({ format: true}, (err, svg) => {
                 if (err) {
                     console.error('Failed to export SVG', err);
                 } else {
                     const blob = new Blob([svg], { type: 'image/svg+xml' });
                     saveAs(blob, 'diagram.svg');
                 }
             });
        } catch (err) {
            console.error('Failed to export SVG', err);
        }
    };

    // 下载为 PNG 文件
    const handleDownloadPNG = async () => {
        try {
            const container = bpmnModeler.get('canvas')._container;
            const dataUrl = await domtoimage.toPng(container);
            const blob = await fetch(dataUrl).then((res) => res.blob());
            saveAs(blob, 'diagram.png');
        } catch (err) {
            console.error('Failed to export PNG', err);
        }
    };







    return (
        <div style={{ display: 'flex', alignItems: 'center' }}>
           <Popover placement={'bottom'} content={"保存"}> <Button size={'large'} icon={<SaveOutlined />} onClick={() => saveHand()}  type="text" /></Popover>
            <Divider  type="vertical" />
            <Popover placement={'bottom'} content={
                <div style={{display:'flex',flexDirection:'column'}}>
                    <Button size={'middle'}   type="text" onClick={() => handleDownloadBPMN()} >下载为BPMN</Button>
                    <Button size={'middle'} style={{marginLeft:'10px'}}   type="text" onClick={() => handleDownloadXML()} >下载为XML</Button>
                    <Button size={'middle'}  style={{marginLeft:'10px'}}  type="text" onClick={() => handleDownloadSVG()} >下载为SVG</Button>
                    <Button size={'middle'}  style={{marginLeft:'10px'}}  type="text" onClick={() => handleDownloadPNG()} >下载为PNG</Button>
                </div>
            }><Button size={'large'}  icon={<DownloadOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"预览"}><Button size={'large'}  onClick={() => handlePreview()} icon={<EyeOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"放大"}><Button size={'large'} onClick={() => handleZoomIn()}   icon={<ZoomInOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"缩小"}><Button size={'large'}  onClick={() => handleZoomOut()} icon={<ZoomOutOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"撤销"}><Button size={'large'}  onClick={() => handleUndo()} icon={<UndoOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"恢复"}><Button size={'large'}  onClick={() => handleRedo()} icon={<RedoOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"擦除重做"}> <Button size={'large'} onClick={() => handleErase()}  icon={<DeleteOutlined />} type="text" /></Popover>
            <Divider type="vertical" />
            <Popover placement={'bottom'} content={"返回"}><Button size={'large'} onClick={() => navigate(-1)}  icon={<RollbackOutlined />} type="text" /></Popover>
        </div>
    );
};

export default ProcessTools;
